package com.zimi.core.config;

import com.zimi.core.security.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@SpringBootConfiguration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private final Authent customAuthProvider;

    private final AuthenctiationSuccess authenctiationSuccess;

    private final AuthenctiationFailure authenctiationFailure;

    private final AccessDenied accessDenied;
    private String[] ANONYMOUS_PATH = new String[]{"/wx/**", "/app/**", "/file/**", "/assets/**", "/error/**", "/auth/**", "/swagger-ui.html", "/webjars/**", "/swagger-resources/**", "/*/api-docs", "/configuration/**", "/attachment/**", "/system/encrypt", "/actuator/**", "/h2/**"};
    private String[] ANONYMOUS_RES_PATH = new String[]{"/", "/*.html", "/favicon.ico", "/**/*.html", "/**/*.css", "/layui/**", "/dist/**", "/**/*.js"};

    @Autowired
    public SecurityConfig(Authent customAuthProvider, AuthenctiationSuccess authenctiationSuccess, AuthenctiationFailure authenctiationFailure, AuthenctiationValidate authenctiationValidate, AccessDenied accessDenied) {
        this.customAuthProvider = customAuthProvider;
        this.authenctiationSuccess = authenctiationSuccess;
        this.authenctiationFailure = authenctiationFailure;
        this.accessDenied = accessDenied;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationFilter ValidateCodeFilterBean() throws Exception {
        return new AuthenticationFilter();
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(customAuthProvider);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
                .antMatchers("/captcha/*", "/static/**", "/public/**", "/registry/*", "/reset-password/*");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
                // 由于使用的是JWT，我们这里不需要csrf
                .csrf().disable()
                // 基于token，所以不需要session
                //.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .authorizeRequests()
                // 允许对于网站静态资源的无授权访问
                .antMatchers(HttpMethod.GET, ANONYMOUS_RES_PATH
                ).permitAll()
                //允许ajax的option请求
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                .antMatchers(ANONYMOUS_PATH).permitAll()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated().and()
                .formLogin().loginPage("/login")
                .successHandler(authenctiationSuccess)
                .failureHandler(authenctiationFailure).permitAll().and()
                .logout().logoutSuccessUrl("/login").permitAll().and()
                .exceptionHandling().accessDeniedHandler(accessDenied);

        // 添加 filter
        http
                .addFilterBefore(ValidateCodeFilterBean(), UsernamePasswordAuthenticationFilter.class);

        // 禁用缓存
        http.headers().cacheControl();
        //允许跨域
        http.headers().frameOptions().disable();
    }
}